package com.laundry.user.ui.profile

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.laundry.user.data.model.User
import com.laundry.user.data.repository.UserRepository
import com.laundry.user.ui.auth.LoginActivity
import kotlinx.coroutines.launch

class ProfileFragment : Fragment() {

    private lateinit var userRepository: UserRepository
    private lateinit var avatarImageView: ImageView
    private lateinit var nicknameTextView: TextView
    private lateinit var phoneTextView: TextView
    private lateinit var pointsTextView: TextView
    private lateinit var membershipTextView: TextView

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        userRepository = UserRepository(requireContext())
        return createView()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadUserInfo()
    }

    private fun createView(): View {
        val scrollView = ScrollView(requireContext()).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }

        val mainLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
        }

        // 用户信息头部
        val headerLayout = createHeaderLayout()
        
        // 功能菜单
        val menuLayout = createMenuLayout()

        mainLayout.addView(headerLayout)
        mainLayout.addView(menuLayout)

        scrollView.addView(mainLayout)
        return scrollView
    }

    private fun createHeaderLayout(): LinearLayout {
        val headerLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(20, 40, 20, 40)
            background = createHeaderBackground()
        }

        // 用户头像和基本信息
        val userInfoLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.HORIZONTAL
            gravity = android.view.Gravity.CENTER_VERTICAL
        }

        avatarImageView = ImageView(requireContext()).apply {
            layoutParams = LinearLayout.LayoutParams(80, 80)
            setImageResource(android.R.drawable.ic_menu_myplaces)
            background = createAvatarBackground()
        }

        val infoLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(20, 0, 0, 0)
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        nicknameTextView = TextView(requireContext()).apply {
            text = "用户昵称"
            textSize = 18f
            setTextColor(android.graphics.Color.WHITE)
        }

        phoneTextView = TextView(requireContext()).apply {
            text = "手机号"
            textSize = 14f
            setTextColor(android.graphics.Color.parseColor("#E0E0E0"))
            setPadding(0, 4, 0, 0)
        }

        infoLayout.addView(nicknameTextView)
        infoLayout.addView(phoneTextView)

        userInfoLayout.addView(avatarImageView)
        userInfoLayout.addView(infoLayout)

        // 积分和会员信息
        val statsLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.HORIZONTAL
            setPadding(0, 20, 0, 0)
        }

        val pointsLayout = createStatItem("积分", "0")
        pointsTextView = pointsLayout.getChildAt(1) as TextView

        val membershipLayout = createStatItem("会员等级", "普通会员")
        membershipTextView = membershipLayout.getChildAt(1) as TextView

        statsLayout.addView(pointsLayout)
        statsLayout.addView(membershipLayout)

        headerLayout.addView(userInfoLayout)
        headerLayout.addView(statsLayout)

        return headerLayout
    }

    private fun createStatItem(title: String, value: String): LinearLayout {
        val layout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            gravity = android.view.Gravity.CENTER
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        val titleView = TextView(requireContext()).apply {
            text = title
            textSize = 12f
            setTextColor(android.graphics.Color.parseColor("#E0E0E0"))
            gravity = android.view.Gravity.CENTER
        }

        val valueView = TextView(requireContext()).apply {
            text = value
            textSize = 16f
            setTextColor(android.graphics.Color.WHITE)
            gravity = android.view.Gravity.CENTER
            setPadding(0, 4, 0, 0)
        }

        layout.addView(titleView)
        layout.addView(valueView)

        return layout
    }

    private fun createMenuLayout(): LinearLayout {
        val menuLayout = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(0, 20, 0, 0)
        }

        val menuItems = listOf(
            "我的地址" to { /* TODO: 跳转到地址管理 */ },
            "我的收藏" to { /* TODO: 跳转到收藏列表 */ },
            "优惠券" to { /* TODO: 跳转到优惠券 */ },
            "客服中心" to { /* TODO: 跳转到客服 */ },
            "设置" to { /* TODO: 跳转到设置 */ },
            "关于我们" to { /* TODO: 跳转到关于页面 */ },
            "退出登录" to { logout() }
        )

        menuItems.forEach { (title, action) ->
            val menuItem = createMenuItem(title, action)
            menuLayout.addView(menuItem)
        }

        return menuLayout
    }

    private fun createMenuItem(title: String, action: () -> Unit): LinearLayout {
        val menuItem = LinearLayout(requireContext()).apply {
            orientation = LinearLayout.HORIZONTAL
            gravity = android.view.Gravity.CENTER_VERTICAL
            setPadding(20, 20, 20, 20)
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            background = createMenuItemBackground()
            setOnClickListener { action() }
        }

        val iconView = ImageView(requireContext()).apply {
            layoutParams = LinearLayout.LayoutParams(40, 40)
            setImageResource(android.R.drawable.ic_menu_manage)
        }

        val titleView = TextView(requireContext()).apply {
            text = title
            textSize = 16f
            setTextColor(android.graphics.Color.parseColor("#333333"))
            setPadding(20, 0, 0, 0)
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        val arrowView = ImageView(requireContext()).apply {
            layoutParams = LinearLayout.LayoutParams(24, 24)
            setImageResource(android.R.drawable.ic_media_play)
        }

        menuItem.addView(iconView)
        menuItem.addView(titleView)
        menuItem.addView(arrowView)

        return menuItem
    }

    private fun loadUserInfo() {
        lifecycleScope.launch {
            try {
                val user = userRepository.getCurrentUser()
                if (user != null) {
                    updateUserInfo(user)
                }
            } catch (e: Exception) {
                Toast.makeText(requireContext(), "加载用户信息失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun updateUserInfo(user: User) {
        nicknameTextView.text = user.nickname.ifEmpty { "未设置昵称" }
        phoneTextView.text = user.phone
        pointsTextView.text = user.points.toString()
        membershipTextView.text = getMembershipText(user.membershipLevel)
    }

    private fun getMembershipText(level: Int): String {
        return when (level) {
            0 -> "普通会员"
            1 -> "银卡会员"
            2 -> "金卡会员"
            3 -> "钻石会员"
            else -> "普通会员"
        }
    }

    private fun logout() {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle("退出登录")
            .setMessage("确定要退出登录吗？")
            .setPositiveButton("确定") { _, _ ->
                lifecycleScope.launch {
                    userRepository.logout()
                    val intent = Intent(requireContext(), LoginActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                    startActivity(intent)
                    requireActivity().finish()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun createHeaderBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable(
            android.graphics.drawable.GradientDrawable.Orientation.TOP_BOTTOM,
            intArrayOf(
                android.graphics.Color.parseColor("#2196F3"),
                android.graphics.Color.parseColor("#1976D2")
            )
        )
        return drawable
    }

    private fun createAvatarBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.WHITE)
        drawable.cornerRadius = 40f
        return drawable
    }

    private fun createMenuItemBackground(): android.graphics.drawable.Drawable {
        val drawable = android.graphics.drawable.GradientDrawable()
        drawable.setColor(android.graphics.Color.WHITE)
        drawable.setStroke(1, android.graphics.Color.parseColor("#E0E0E0"))
        return drawable
    }
}
